<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>首页</title>
    <link rel="stylesheet" href="layui/css/layui.css">
    <style>
        .cashStateDiv tbody .layui-table-cell{
            height:90px;
            line-height: 90px;
        }
        body {
            background:url(img/bbgg.jpg);
        }

    </style>
</head>
<body>

<!--个人信息编辑弹出框-开始-->
<div id="updateInfoDiv" style="display: none;padding-top: 30px;">
    <form class="layui-form" lay-filter="dataFrm" id="dataFrm">
        <input type="hidden" name="id" class="layui-input">

        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">用户名：</label>
                <div class="layui-input-inline">
                    <input type="text" name="userName" lay-verify="required" readonly autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">昵称：</label>
                <div class="layui-input-inline">
                    <input type="text" name="nickName" lay-verify="required" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label">头像：</label>
                <div class="layui-input-block">
                    <button type="button" class="layui-btn layui-btn-radius" id="test1">更换头像</button>
                    <div id="editUploadBtn" style="display: none">
                        <button type="button" class="layui-btn layui-btn-normal layui-btn-radius" id="uploadBtn">点击上传</button>
                    </div>
                        <div class="layui-upload-list">
                        <img class="layui-upload-img" id="demo1" width="170px" height="170px" style="border-radius: 50%;border: 1px solid whitesmoke">
                        <p id="demoText"></p>
                    </div>

                </div>
            </div>

            <!-- 存放图片路径 -->
            <input type="hidden" name="avatar" id="avatarUrl" lay-verify="avatar" autocomplete="off" class="layui-input">

            <div class="layui-inline">
                <label class="layui-form-label">性别：</label>
                <div class="layui-input-inline">
                    <input type="radio" name="gender" value="男" title="男">
                    <input type="radio" name="gender" value="女" title="女">
                    <input type="radio" name="gender" value="" title="保密" checked>
                </div>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label">联系电话：</label>
                <div class="layui-input-inline">
                    <input type="text" name="telephone" lay-verify="telephone" placeholder="请输入联系电话" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label">QQ邮箱：</label>
                <div class="layui-input-inline">
                    <input type="text" name="email" lay-verify="required|qqEmail" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label">地址：</label>
                <div class="layui-input-inline">
                    <input type="text" name="address" lay-verify="address" autocomplete="off" class="layui-input">
<!--                    <select name="province" data-area="广东省" lay-filter="province"><option value="">选择省</option></select>-->
<!--                    <select name="city" data-area="广州市" lay-filter="city"><option value="">选择市</option></select>-->
<!--                    <select name="district" data-area="天河区" lay-filter="district"><option value="">选择区</option></select>-->
                </div>
            </div>


        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="button" class="layui-btn" lay-submit="" lay-filter="submit">提交</button>
                <button type="button" class="layui-btn layui-btn-primary" id="closeInfo">关闭</button>
            </div>
        </div>
    </form>
</div>
<!--个人信息编辑弹出框-结束-->

<!--<div class="layui-container" style="width: 710px;height: 600px;margin-top: 0px;">-->
<div class="layui-container" style="width: 100%;margin-top: 0px;">
    <ul class="layui-nav">
        <li class="layui-nav-item layui-logo">
            <i class="layui-icon">&#xe653;</i>&nbsp;Goods_Order
        </li>
        <li class="layui-nav-item layui-this">
            <a href="">首页</a>
        </li>
        <li class="layui-nav-item">
            <a href="javascript:;" id="myOrder">我的订单<span class="layui-badge" id="orderNumber"></span></a>
        </li>
        <li class="layui-nav-item layui-layout-right" lay-unselect="">
            <input type="hidden" id="userId">
            <a href="javascript:;"><img id="avatar" class="layui-nav-img"><span id="nickName">加载中</span></a>
            <dl class="layui-nav-child">
                <dd><a href="javascript:;" id="info">我的资料</a></dd>
                <hr>
                <dd><a href="javascript:;" id="logOutBtn">退出登录</a></dd>
            </dl>
        </li>
    </ul>
</div>
<br>

    <script type="text/html" id="userBarDemo">
        <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="deleteOrder" id="deleteOrder">删除订单</a>
    </script>
    <!-- 用户订单表 -->
    <div id="orderDiv" style="display: none">
        <table class="layui-hide" id="orderTable" lay-filter="orderTable"></table>
    </div>

    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-radius layui-btn-sm"  lay-event="look"><i class="layui-icon">&#xe615;</i>查看</a>
        <a class="layui-btn layui-btn-normal layui-btn-radius layui-btn-sm" lay-event="order"><i class="layui-icon">&#xe698;</i>订购</a>
    </script>

<div class="layui-container" style="height: 600px;margin-top: 0px;">
    <div class="layui-col-xs12 layui-col-md10 layui-col-md-offset1">

        <div class="layui-carousel" id="test2" style="border: 1px solid whitesmoke;">
            <div carousel-item="">
                <div><img src="img/1.png" height="450px" width="100%" style="border-radius: 1%;"></div>
                <div><img src="img/2.png" height="450px" width="100%" style="border-radius: 1%;"></div>
                <div><img src="img/3.png" height="450px" width="100%" style="border-radius: 1%;"></div>
            </div>
        </div><br>

        <div class="demoTable">
            商品：
            <div class="layui-inline">
                <input class="layui-input" id="send_name" placeholder="输入关键字" autocomplete="off">
            </div>
            单价：
            <div class="layui-inline">
                <input class="layui-input" id="send_price" autocomplete="off">
            </div>
            简介：
            <div class="layui-inline">
                <input class="layui-input" id="send_content" placeholder="输入关键字" autocomplete="off">
            </div>

            <button class="layui-btn layui-btn-normal" data-type="reload" id="do_search"><i class="layui-icon">&#xe615;</i>搜索</button>
        </div>

        <div class="cashStateDiv">
            <table class="layui-hide" style="height: 90px;line-height: 90px" id="test" lay-filter="test"></table>
        </div>

    </div>


    <script src="layui/layui.js" charset="utf-8"></script>
    <script src="js/jquery-3.3.1.js"></script>
    <script src="js/address-picker.js" charset="utf-8"></script>
    <script>

        layui.config({
            base: 'js/' //假设这是你存放拓展模块的根目录
        }).extend({ //设定模块别名
            common: 'common' //如果 common.js 是在根目录，也可以不用设定别名
        });

        layui.use(['table','jquery','element','carousel','form','upload','util','common'], function(){
            var element = layui.element; //导航的hover效果、二级菜单等功能，需要依赖element模块
            var table = layui.table;
            var $ = layui.jquery;
            var carousel = layui.carousel;
            var form = layui.form;
            var upload = layui.upload;
            var util = layui.util;
            var common = layui.common;

            //三级地址联动
            common.showCity('province', 'city', 'district');

            //layui返回顶部
            util.fixbar({
                top:true
                , css: { right: 15, bottom: 35 }
                , bgcolor: 'display:block;'
                ,showHeight:100
                , click: function (type) {
                    if (type === 'top') {
                        $('.layui-body').animate({//主要代码
                            scrollTop: 0
                        }, 1000);
                    }
                }
            });
            //轮播
            carousel.render({
                elem: '#test2'
                ,interval: 1800
                ,anim: 'fade'
                ,height: '450px'
                ,width: '100%'
            });
            var tableIns = table.render({
                elem: '#test'
                ,url:'/goodsApi/goodsList'
                ,title: '商品列表'
                ,cols: [
                    [
                        // {field:'id',  title: '#', sort: true,width: 60}
                        {field: 'picture', title: '图片',templet:img,width: 140}
                        , {field:'name',title: '商品'}
                        ,{field:'price',  title: '单价',width: 80}
                        ,{field:'content', title: '简介'}
                        ,{field:'typeId',  title: '分类',width: 80,templet:function(data){
                            return data.type.name
                            }
                        }
                        ,{fixed: 'right', title:'操作', toolbar: '#barDemo', align:'center'}

                    ]
                ]
                ,page: true
            });

            // 执行搜索，表格重载
            $('#do_search').on('click', function () {
                // 搜索条件
                var send_name = $('#send_name').val();
                var send_price = $('#send_price').val();
                var send_type = $('#send_type').val();
                var send_content = $('#send_content').val();
                table.reload('test', {
                    method: 'get'
                    , where: {
                        'name': send_name,
                        'price': send_price,
                        'content': send_content
                    }
                    , page: {
                        curr: 1
                    }
                });
            })

            var jq = $;
            //监听菜品表行工具事件
            table.on('tool(test)', function(obj){
                var data = obj.data;
                if(obj.event === 'look'){
                    var id = data.id; //传给弹出页面参数
                    var url = 'info.html?id='+data.id;
                    encodeURI(url);
                    // location.href=url;
                    window.open(url);
                }
                if(obj.event === 'order'){
                    layer.confirm('确认订购【'+data.name+'】么', function(index){
                        var goodsId={'goodsId':data.id};
                        $.post("/orderApi/insertOrder",goodsId,function (res) {
                            layer.close();
                            layer.alert(res.data, {icon: 1});
                            //加载用户订单数量
                            loadOrderNum();
                        })
                    });

                }
            });

            //监听订单表行工具事件
            table.on('tool(orderTable)', function(obj){
                var data = obj.data;
                if(obj.event === 'deleteOrder'){
                    layer.confirm('真的删除订单么', function(index){
                        $.ajax({
                            type: 'DELETE',
                            url: '/orderApi/deleteOrder',
                            data: {'id':data.id},
                            success: function (res){
                                obj.del();
                                layer.close();
                                layer.msg(res.data);
                            }
                        })
                    });

                }
            });

            //弹出编辑个人信息弹出框
            function openUpdateInfoDiv(data){
                infoDiv=layer.open({
                    type:1,
                    title:'我的资料',
                    area:['370px','680px'],
                    content:$('#updateInfoDiv'),
                    success:function () {
                        //初始化表单
                        form.val("dataFrm",data);
                        //隐藏上传图片按钮
                        $('#editUploadBtn').attr('style','display:none')
                        $('#demo1').attr('src', data.avatar);
                    }
                })

            }

            //普通图片上传
            var uploadInst = upload.render({
                elem: '#test1'
                ,url: '/uploadApi/upload/0'
                ,auto: false
                ,size: 1024 //限制文件大小，单位 KB
                ,accept: 'images'   //文件类型
                ,acceptMime: 'image/*'
                ,field: 'uploadFile'
                // ,bindAction: '#uploadBtn'//绑定上传按钮
                , choose: function (obj) {

                    //选完图片后
                    obj.preview(function (index, file, result) {
                        //显示上传图片按钮
                        $('#editUploadBtn').attr('style','display:inline')
                        console.log(index); //得到文件索引
                        console.log(file); //得到文件对象
                        //选图片就将#picture的输入框清空
                        $('#avatarUrl').val('');
                        //显示预览图片
                        $('#demo1').attr('src', result); //图片链接（base64）
                    });
                }
                , done: function (res) {
                    //关闭加载层
                    layer.closeAll('loading');
                    if (res.code >0) {
                        return layer.msg(res.data);
                    }else{
                        layer.alert('上传成功');
                        //将服务器存放的图片路径设置在#picture的输入框
                        $('#avatarUrl').val(res.data.src);
                    }
                    //上传成功
                }
                , error: function () {
                    //关闭加载层
                    layer.closeAll('loading');
                    //演示失败状态，并实现重传
                    var demoText = $('#demoText');
                    demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                    demoText.find('.demo-reload').on('click', function () {
                        uploadInst.upload();
                    });
                }
            });

            //自定义绑定上传按钮
            $('#uploadBtn').click(function () {
                //加载层
                layer.load(2);
                uploadInst.upload();
            })

            //提交
            form.on("submit(submit)",function (obj) {
                //序列化表单数据
                var params=$("#dataFrm").serialize();
                //请求后端添加或编辑方法
                $.ajax({
                    type:'PUT',
                    url:'/userApi/updateUserById',
                    data:params,
                    success:function (data) {
                        if(data.code===200){
                            layer.msg(data.data)
                            //加载用户信息
                            loadInfo();
                        }else{
                            layer.alert('服务器异常', {icon: 2});
                        }

                        //关闭弹出层
                        layer.close(infoDiv)

                    }
                })

            })

            // 表格格式化  -  img 渲染
            function img(cellvalue) {
                console.log(cellvalue);
                return "<img src='" + cellvalue.picture + "' height=\"90\" width=\"100\" />";
            }

            form.verify({
                telephone: [/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/,"请输入正确的电话"],
                qqEmail: function(value){
                    var emailRegex=new RegExp("[1-9]\\d{7,10}@qq\\.com");
                    if(!value.match(emailRegex)) {
                        return "请输入正确的邮箱";
                    }
                },
                avatar: function(value){
                    if(value.length == 0){
                        return "请先上传头像";
                    }
                },
                address: [/^[\u4e00-\u9fa5]+$/, '请输入中文地址'],
            });

            //加载用户信息
            function loadInfo(){
                $.post('/userApi/getUser',function (res) {
                    $('#userId').val(res.data.id);
                    $('#nickName').text(res.data.nickName);
                    $('#avatar').attr('src',res.data.avatar);
                })
            }

            //加载用户订单数量
            function loadOrderNum(){
                $.get('/orderApi/getOrderNumber',function (res) {
                    $('#orderNumber').text(res.data)
                })
            }

            $(function () {

                $('#closeInfo').click(function () {
                    layer.close(infoDiv);
                })
                //加载用户信息
                // $.get('/accountApi/getLoginObj/user',function (res) {
                //     $('#userId').val(res.data.id);
                //     $('#nickName').text(res.data.nickName);
                //     $('#avatar').attr('src',res.data.avatar);
                // })
                //加载用户信息
                loadInfo();

                //加载用户订单数量
                loadOrderNum();

                //个人信息按钮
                $('#info').click(function () {
                    //请求用户个人信息
                    $.post('/userApi/getUser',function (res) {

                        console.log(res.data)
                        openUpdateInfoDiv(res.data);
                    })

                })

                //注销按钮
                $('#logOutBtn').click(function () {
                    layer.confirm('真的退出么', function(index){
                        layer.close(index);
                        layer.load();
                        $.get("/accountApi/logout",function () {
                            location.href="login.html";
                        })
                    });
                })

                //查看用户订单
                $('#myOrder').click(function (){
                    orderDiv=layer.open({
                        type:1,
                        title:'<i class="layui-icon layui-icon-cart"></i>&nbsp;我的订单',
                        area:['720px','350px'],
                        content:$('#orderDiv'),
                        success:function () {

                            //加载用户订单表
                            table.render({
                                elem: '#orderTable'
                                ,url:'/orderApi/userOrderList'
                                ,title: '订单列表'
                                ,limit: 5
                                ,cols: [
                                    [
                                        {field:'id', title: '#', sort: true,width: 60}
                                        ,{field:'goods', title: '商品',templet:function(data){
                                            return data.goods.name
                                            }
                                        }
                                        ,{field:'price', title: '单价', templet:function(data){
                                            return data.goods.price
                                            }
                                        }
                                        ,{field:'content', title: '简介',templet:function(data){
                                            return data.goods.content
                                            }
                                        }
                                        ,{field:'date', title: '下单时间'}
                                        ,{field:'state', title: '订单状态',align:'center',templet:function(data){
                                            return data.state==1?'<button type="button" class="layui-btn layui-btn-xs">已发货</button>':'<button type="button" class="layui-btn layui-btn-primary layui-btn-xs">未发货</button>';
                                        }

                                    }
                                        ,{fixed: 'right', title:'操作', toolbar: '#userBarDemo', align:'center'}

                                    ]
                                ]
                                ,page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                                    layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                                    //,curr: 5 //设定初始在第 5 页
                                    ,groups: 1 //只显示 1 个连续页码
                                    ,first: false //不显示首页
                                    ,last: false //不显示尾页

                                }
                                ,text: {
                                    none: '你还没下单呢' //默认：显示 无数据。
                                }
                            });

                        }
                    })
                })

            })
        });
    </script>

</div>
</body>
</html>